/**
 * @Author: likang xie
 * @Date: 2019-11-06 17:38:23
 * @Usage Request方法二次封装
 */

import config from "@/config";
import store from "@/store";
import toast from "@/utils/toast";

// ---- 封装增、删、改、查方法 ----
let request = new Object();

["post", "del", "put", "get"].forEach(method => {
  request[method] = (url, params, extra = {}) =>
    new Promise((resolve, reject) => {
      let {
        title = "请稍后..",
        showLoading = true,
        showErrorToast = true,
        headers = {
          "content-type": "application/x-www-form-urlencoded"
        }
      } = extra;

      // 显示全屏loading
      // showLoading &&
      //   uni.showLoading({
      //     title,
      //     mask: true
      //   });

      let userInfo = uni.getStorageSync("userInfo") || {};

      // #ifdef H5
      if (process.env.NODE_ENV == "development") {
        config.remote = config.remote;
      } else {
        url = url.replace("/doc", "");
      }
      
      url = url.replace("/doc", "");
      // #endif
      // #ifndef H5
      url = url.replace("/doc", "");
      // #endif

      // 开始发送请求
      uni
        .request({
          url: config.remote + url,
          header: headers,
          data: {
            ...params,
            token: userInfo.token || ""
          },
          method
        })
        .then(chunk => {
          // uni.hideLoading();

          let [err, res] = chunk;

          if (res) {
			  
            let { code, message } = res.data;
			
            // 更改一下正确状态码，强迫症
            if (code === 1000 || code === '1000') res.data.code = 200;

            // 未登录/重新登录/Token过期
            if (code === 1011 || code === 1013) {
              toast("未登录或已过期");
              store.dispatch("SET_USER_INFO", "");
              uni.setStorageSync("timUserSign", "");
              return uni.navigateTo({
                url: "/user/login"
              });
            }

            // 其他错误提示
            if (code && code != 1000 && showErrorToast){
				 toast(message || "未知错误")
			}
            resolve(res.data);
          } else {
            toast("请求失败，请重试", "error");
			uni.hideLoading();
			console.log("----->请求失败:",err);
            reject(err);
          }
        });
    });
});

export default request;
